import fs from 'fs'
import request from 'request'
import { generateFileName } from './tools'

const dirPath = 'file'

// 创建文件夹
if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath)
}

function Download (list) {
    this.list = list // 待下载url列表
    this.pathList = [] // 待下载url列表
}

Download.prototype.request = function (url, resolve, reject) {
    let type = 'jpg'
    const path = `${dirPath}/${generateFileName()}.${type}`
    const writeStream = fs.createWriteStream(path)

    // 文件写入完成
    writeStream.on('finish', () => {
        this.pathList.push(path)

        // 全部下载完成
        if (this.pathList.length === this.list.length) {
            resolve(this.pathList)
        }
    })

    // 请求文件
    request.get(url)
        .pipe(writeStream)
        .on('end', writeStream.end)
        .on('error', function(err) {
            reject(err)
        })
}
Download.prototype.start = function () {
    return new Promise((resolve, reject) => {
        this.list.forEach(url => {
            this.request(url, resolve, reject)
        })
    })
}

export default Download
